import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnInit,
  OnDestroy,
  ViewEncapsulation,
  EventEmitter
} from "@angular/core";
import { Router, RouterModule, ActivatedRoute } from "@angular/router";
import { DomSanitizer } from "@angular/platform-browser";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";

export const DISPLAY_STRATEGY_NONE = 0;
export const DISPLAY_STRATEGY_REPLACE = 1;

const getFirstChild = arr => arr[0] && arr[0].children ? getFirstChild(arr[0].children) : arr[0];

@Component({
  selector: "tab-list",
  // changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  templateUrl: "./tab-list.component.html",
  styleUrls: [
    // "./tab-list.component.less" //这里作为给其他组件使用，本组件只作为行为逻辑，不应包含样式
  ],
  inputs: [
    "tabClickSource",
    "isNavTab",
    "listData",
    "baseUrl",
    "autoClickFirst",
    "autoClickFirstForce",
    "activeOptions",
    "refreshSource",
    "menuLeft"
  ],
  outputs: [
    "tabClick"
  ]
})
export class TabListComponent implements OnInit, OnDestroy {
  currentTab;
  listData;
  autoClickFirst = false;
  autoClickFirstForce = false;
  firstClicked = false;
  defaultUrl: string = "";
  tabClickSource: EventEmitter<any>;
  refreshSource: Observable<any>;
  activeOptions = {
    exact: false
  };

  constructor(private router: ActivatedRoute, private sanitizer: DomSanitizer) {

  }

  tabClick = new EventEmitter();
  routerSubscription: Subscription;

  ngOnChanges(changes) {
    if (changes.listData && changes.listData.currentValue) {
      if (this.autoClickFirstForce) {
        setTimeout(() => this.onClick(getFirstChild(this.listData)));
      }
    }
  }

  ngOnInit() {
    // console.debug("Tab List Init: ", this);
    if (this.autoClickFirst) {
      // console.debug("Auto Click First: ", this.listData);
      setTimeout(() => this.onClick(getFirstChild(this.listData)));
    }
    if (this.tabClickSource) {
      this.tabClickSource.subscribe(tab => this.onClick(tab));
    }
  }

  ngOnDestroy() {
    this.routerSubscription ? this.routerSubscription.unsubscribe() : null;
  }

  onClick(tab) {
    this.currentTab = tab;
    this.tabClick.emit(tab);
  }

  handleSubToggle(tab) {
    if (tab.abstract) {
      this.onClick(getFirstChild(tab.children))
    }
  }

  getSubToggleLable(tab) {
    return tab.textStrategy === DISPLAY_STRATEGY_NONE ?
      tab.text :
      tab.textStrategy === DISPLAY_STRATEGY_REPLACE ?
        this.currentTab && tab.children.some(item => item.key === this.currentTab.key) ?
          this.currentTab.text :
          tab.abstract ?
            getFirstChild(tab.children).text :
            tab.text :
        "";
  }

  getSubToggleClass(tab) {
    return this.currentTab && tab.children.some(item => item.key === this.currentTab.key);
  }

  getHtml(innerHTML) {
    return this.sanitizer.bypassSecurityTrustHtml(innerHTML);
  }

  trackByText(tab) {
    return tab.text;
  }
}